package com.xinongbest.mall.controller;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/upload/image")
public class UploadImageController {
    private static final String PATH_TO_FOLDER = "";

    private static final int THUMB_WIDTH = 200;

    private static final int THUMB_HEIGHT = 200;

    @PostMapping("/uploadImage")
    public String uploadImage(@RequestPart(value = "file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            Path path = Paths.get(PATH_TO_FOLDER + fileName);
            Files.write(path, bytes);

            String thumbnailName = "thumb_" + fileName; // change name for thumb image
            File thumbnailFile = new File(PATH_TO_FOLDER + thumbnailName);

            Thumbnails.of(PATH_TO_FOLDER + fileName)
                    .size(THUMB_WIDTH, THUMB_HEIGHT)
                    .keepAspectRatio(true)
                    .toFile(thumbnailFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Success";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws Exception {

        String url = "http://your-upload-api.com/upload";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, Object> params= new LinkedMultiValueMap<>();
        // params.add("file", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));

        params.add("file", new ByteArrayResource(file.getBytes()));
        params.add("filename", file.getOriginalFilename());

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);

        RestTemplate restTemplate = new RestTemplate();

        String response = restTemplate.postForObject(url,requestEntity,String.class);

        return response;

    }

}
